import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-11-09
 * Time: 10:42
 */

public class UdpEchoClient {
    //网络编程前提
    private DatagramSocket socket = null;
    //要指定服务器的IP和端口
    private String serverIP;
    private int serverPort;

    //构造方法 创建实例 传服务器的IP和端口 客户端的端口 系统自动分配
    public UdpEchoClient(String IP, int port) throws SocketException {
        socket = new DatagramSocket(); //不传参数 系统自动分配
        serverIP = IP;
        serverPort = port;
    }

    //启动客户端
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //从控制台读取用户的数据
            System.out.println("-> ");
            String request = scanner.next();
            //1.将输入的内容构造成一个UDP数据报 并发送
            //直接构造 不用创建空的接收
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    //指定发给服务器的地址 注意写法
                    InetAddress.getByName(serverIP), serverPort);
            //构造完成之后 发送
            socket.send(requestPacket);
            //发送之后 再读取服务器返回的数据 并解析
            //接收都是先创建空的 然后接收
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            //再将数据报改为String对象
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            //4显示到控制台
            System.out.printf("req: %s,resp: %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}


